import { Component, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core';
import { HttpService } from '@kylin/http';
import { NzMessageService } from 'ng-zorro-antd';
import { LoginService } from '../login.service';
import { FormBuilder, FormGroup, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
import { CustomValidators } from '@kylin/validators';

@Component({
    selector: 'kylin-phone-login',
    templateUrl: './phone-login.component.html',
    styleUrls: ['./phone-login.component.less']
})
export class PhoneLoginComponent implements OnInit, OnDestroy {
    @Input() successHandler: any;
    @Output() loginSuccess = new EventEmitter<any>();
    @Input() loginByPhone: boolean;
    @Output() loginByPhoneChange = new EventEmitter<boolean>();
    loginForm: FormGroup;
    logging = false;
    effectiveTime = 90; // 90s
    inEffectiveTime = false;
    timer: any;

    constructor(private http: HttpService, private fb: FormBuilder, private message: NzMessageService, private loginService: LoginService) {
    }

    ngOnInit() {
        this.loginFormInit();
    }

    loginFormInit() {
        this.loginForm = this.fb.group({
            phoneNumber: [null, [Validators.required, CustomValidators.phoneNumberValidator()]],
            validCode: [null, [Validators.required]]
        });
    }

    sendSMS() {
        if (!this.loginForm.value['phoneNumber']) {
            this.loginForm.get('phoneNumber').markAsDirty();
            this.loginForm.get('phoneNumber').updateValueAndValidity();
            return;
        }
        if (this.loginForm.get('phoneNumber').errors || this.inEffectiveTime) {
            return;
        }
        this.http.get('/smsVerify', {
            smsType: 'AUTH',
            mobile: this.loginForm.value['phoneNumber']
        }).then(rep => {
            if (rep.resp_code !== '10000') {
                this.message.error('获取验证码失败，' + rep.resp_msg);
            } else {
                this.inEffectiveTime = true;
                this.timer = setInterval(() => {
                    this.effectiveTime -= 1;
                    if (this.effectiveTime === 0) {
                        this.effectiveTime = 90;
                        this.inEffectiveTime = false;
                        window.clearInterval(this.timer);
                    }
                }, 1000);
            }
        });
    }

    doLogin() {
        const data = {
            deviceId: this.generateNewDeviceId(),
            username: this.loginForm.value['phoneNumber'] + '|PHONE',
            password: this.loginForm.value['validCode']
        };
        this.logging = true;
        this.loginService.doLogin(data).then(rep => {
            this.logging = false;
            if (rep.resp_code === '10000') {
                this.successHandler(rep);
            } else {
                this.message.error('登录失败,' + rep.resp_msg);
            }
        }).catch(err => {
            this.message.error(err.error.resp_msg);
            this.logging = false;
        })
    }

    generateNewDeviceId() {
        let d = new Date().getTime();
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
            const r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
    }

    changeLoginWay() {
        this.loginByPhone = false;
        this.loginByPhoneChange.emit(false);
    }

    ngOnDestroy(): void {
        window.clearInterval(this.timer);
    }
}
